package com.youku.expression.ast;

import com.youku.expression.TokenType;
import com.youku.expression.environment.Environment;

public abstract class UnaryAst extends Ast {

	protected boolean prefix = false;

	protected String operation;

	public UnaryAst(boolean prefix, Ast ast) {
		super(ast);
		this.prefix = prefix;
	}

	public Ast element() {
		return getChild(0);
	}

	public static UnaryAst build(TokenType type, boolean prefix, Ast ast) {
		if (type == TokenType.INCR) {
			return new IncrAst(prefix, ast);
		} else if (type == TokenType.DECR) {
			return new DecrAst(prefix, ast);
		} else {
			throw new IllegalArgumentException(type + "不是合法参数");
		}
	}

	@Override
	public Object eval(Environment environment) {
		Object originValue = element().eval(environment);

		Object newValue = operate(originValue);

		environment.put(element().getTokenValue(), newValue);

		//如果是先++/--，那么返回++/--后的新值。否则就返回原始值
		if (prefix) {
			return newValue;
		} else {
			return originValue;
		}
	}

	public abstract Object operate(Object element);
}
